<template>
  <div class="container mx-auto px-4 py-8">
    <div class="max-w-2xl mx-auto bg-white rounded-2xl shadow-xl p-6">
      <h2 class="text-2xl font-bold text-gray-800 mb-6 text-center">添加课程类别</h2>
      
      <form @submit.prevent="handleSubmit" class="space-y-4">
        <div>
          <label class="block text-gray-700 mb-2 font-medium">类别名称</label>
          <input 
            v-model="form.name"
            type="text"
            required
            placeholder="请输入课程类别名称"
            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 transition-all"
          />
        </div>
        
        <div>
          <label class="block text-gray-700 mb-2 font-medium">类别描述</label>
          <textarea 
            v-model="form.description"
            rows="3"
            placeholder="请输入课程类别的描述信息"
            class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-blue-500 focus:ring-2 focus:ring-blue-500/30 transition-all"
          ></textarea>
        </div>
        
        <button 
          type="submit"
          class="w-full bg-blue-600 hover:bg-blue-700 text-white py-3 px-4 rounded-lg transition-colors shadow-lg shadow-blue-200/50 mt-6"
        >
          {{ submitting ? '提交中...' : '提交' }}
        </button>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../store/auth'
import api from '../services/api'

const router = useRouter()
const auth = useAuthStore()
const submitting = ref(false)
const form = ref({
  name: '',
  description: ''
})

// 处理表单提交
const handleSubmit = async () => {
  // 验证用户是否已登录
  if (!auth.isLoggedIn || !auth.userId) {
    alert('请先登录后再添加课程类别')
    router.push('/login')
    return
  }
  
  // 表单验证
  if (!form.value.name.trim()) {
    alert('类别名称不能为空')
    return
  }
  
  try {
    submitting.value = true
    
    // 准备提交的数据，确保包含用户ID
    console.log('当前登录状态:', auth.isLoggedIn);
    console.log('当前用户ID:', auth.userId);
    console.log('完整用户信息:', auth.user);

    const categoryData = {
      name: form.value.name,
      description: form.value.description || '',
      userId: auth.userId || auth.user?.id || null,
      createTime: new Date().toISOString()
    }

    console.log('最终提交的类别数据:', categoryData);
    
    try {
      // 调用API添加类别
      const res = await api.addCategory(categoryData)
      if (res && res.data.errno === 0) {
        // API调用成功
        console.log('添加课程类别成功:', res.data.data)
        alert('添加课程类别成功')
        // 清除本地存储的缓存，确保下次加载时从API获取最新数据
        localStorage.removeItem('localCategories')
        router.push('/courses')
      } else {
        // API返回非成功状态，使用本地模拟
        console.log('API返回非成功状态，使用本地模拟')
        handleLocalAdd(categoryData)
      }
    } catch (error) {
      console.log('API调用失败，使用本地模拟:', error.message)
      // API调用失败，使用本地模拟
      handleLocalAdd(categoryData)
    }
  } catch (error) {
    console.error('添加过程中出现异常:', error)
    // 兜底处理
    alert('添加课程类别失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 处理本地添加逻辑
const handleLocalAdd = (categoryData) => {
  // 获取本地存储的类别数据
  let localCategories = JSON.parse(localStorage.getItem('localCategories') || '[]')
  
  // 添加新类别
  localCategories.push(categoryData)
  
  // 保存回本地存储
  localStorage.setItem('localCategories', JSON.stringify(localCategories))
  
  console.log('模拟添加类别成功:', categoryData)
  alert('添加课程类别成功')
  router.push('/courses')
}
</script>